<script lang="ts" setup>
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { formatTime } from "@/utils/time";
const time = ref<string>("");
const timer: any = ref(null);

let lastTime = performance.now();
let timerId;

const props = defineProps({
  height: {
    type: String,
    default: "",
  },
  zIndex: {
    type: Number,
    default: 9,
  },
});

const mainStyle = computed(() => {
  let styles: any = {
    height: props.height,
    "z-index": props.zIndex,
  };
  let styleStr = "";
  for (const key in styles) {
    let value = styles[key];
    if (key && value) {
      styleStr += `${key}:${styles[key]};`;
    }
  }
  return styleStr;
});

const updateTime = () => {
  const now = performance.now();
  const nowDate = new Date();
  const deltaTime = now - lastTime;
  if (deltaTime >= 1000) {
    // 更新时间
    time.value = formatTime(nowDate);
    lastTime = now;
  }
  // 计算剩余时间
  const remainingTime = 1000 - (deltaTime % 1000);
  timerId = setTimeout(updateTime, remainingTime);
};

onMounted(() => {
  // 开始定时器
  timerId = setTimeout(updateTime, 1000);
});

onBeforeUnmount(() => {
  if (timer.value) {
    clearTimeout(timer.value);
    timer.value = null;
  }
});
</script>

<template>
  <div class="comp-time-view" :time-str="timer" :style="mainStyle">
    {{ time }}
  </div>
</template>

<style lang="scss" scoped>
.comp-time-view {
  box-sizing: border-box;
  padding-right: 3vw;
  padding-top: 0.2vw;
  position: absolute;
  right: 0;
  top: 0;
  font-size: 1vw;
  min-width: 20vw;
  text-align: right;
  text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.4);
  color: transparent;
  -webkit-background-clip: text;
  background-image: linear-gradient(to right, #fff 0, #01befc 100%, #fff 0);
}

// @keyframes trans {
//   0%,
//   100% {
//     width: 0;
//     filter: drop-shadow(0 0 0 #fff);
//   }
//   50% {
//     width: 100%;
//     filter: drop-shadow(0 0 25px #00dc82);
//   }
// }

// .comp-time-view {
//   box-sizing: border-box;
//   padding-right: 3vw;
//   padding-top: 0.2vw;
//   position: absolute;
//   right: 0;
//   top: 0;
//   font-size: 1vw;
//   min-width: 20vw;
//   text-align: right;
//   text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.4);

//   color: transparent;
//   text-transform: uppercase;

//   // 动画相关
//   &::before {
//     content: attr(time-str);
//     top: 0;
//     bottom: 0;
//     position: absolute;
//     -webkit-text-stroke: 1px rgba(255, 255, 255, 0.5);
//     // animation: trans 4s ease-in-out infinite;
//     width: 100%;
//     color: #00dc82;
//     -webkit-text-stroke: 1px #00dc82;
//     filter: drop-shadow(0 0 25px #00dc82);
//   }
// }
</style>